package org.wyy.vm.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

import org.wyy.vm.entity.User;
import org.wyy.vm.entity.Video;

import com.alibaba.fastjson.JSON;


public class FileUtils {
	
	public static final String VIDEO_FILE_NAME = "vm.video.data";
	public static final String USER_FILE_NAME = "vm.user.data";

	public static List<Video> readVideoList() {
		String content = FileUtils.read(VIDEO_FILE_NAME);
		return JSON.parseArray(content, Video.class);
	}
	
	public static void writeVideoList(List<Video> content) {
		FileUtils.write(VIDEO_FILE_NAME, JSON.toJSONString(content));
	}
	
	public static List<User> readUserList() {
		String content = FileUtils.read(USER_FILE_NAME);
		return JSON.parseArray(content, User.class);
	}
	
	public static void writeUserList(List<User> content) {
		FileUtils.write(USER_FILE_NAME, JSON.toJSONString(content));
	}

	public static String read(String fileName) {
		Path path = Paths.get(fileName);

		if (!Files.exists(path)) {
			try {
				Files.createFile(path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			return Files.readString(path);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	public static void write(String fileName, String content) {
		Path path = Paths.get(fileName);

		if (!Files.exists(path)) {
			try {
				Files.createFile(path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		try {
			Files.write(path, content.getBytes(), StandardOpenOption.TRUNCATE_EXISTING);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


}
